/**
 * @ClassName: UserInvoiceDao
 * @Description:鍙戠エ琛�
 * @author 832
 * @date 2016-12-08
 */
package com.fzrskj.cloud.free.user.dao;

import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.core.utils.CloudDbDrvUtils;
import com.fzrskj.cloud.free.user.bean.UserInvoice;
import com.fzrskj.cloud.free.user.bean.UserInvoiceView;
import ms.core.consts.SysErr;
import ms.core.db.IDbDrv;
import ms.core.object.CObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class UserInvoiceDao extends CObject {
    //private declarations
    private IDbDrv db = null;

    //constructor function to initialize database access object
    public UserInvoiceDao() {
        db = CloudDbDrvUtils.getDbUtilsDrv();
    }

    //to free resource
    @Override
    public void dispose() {
        db.closeConnection();
    }

    /**
     * 新增发票数据
     *
     * @param cdt
     * @return
     */
    public int addUserInvoice(Map<String, Object> cdt) {
        //if (!cdt.containsKey("agentId")) {
            cdt.put("agentId", CloudContextUtils.getAgentId());
        //}
        int add = db.insertRecord("user_invoice", cdt);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return add;
    }

    /**
     * 查询符合条件的发票总数
     *
     * @param cdt
     * @return
     */
    public int getUserInvoiceCount(Map<String, Object> cdt) {
        //if (!cdt.containsKey("agentId")) {
            cdt.put("agentId", CloudContextUtils.getAgentId());
        //}
        List<Object> list = new ArrayList<>();
        StringBuilder sb = new StringBuilder("select count(id) from user_invoice where 1=1 ");
        for (Map.Entry<String, Object> c : cdt.entrySet()) {
            if (c.getKey().equals("start")) {
                sb.append(" and createTime >=?");
                list.add(c.getValue());
            } else if (c.getKey().equals("end")) {
                sb.append(" and createTime <?");
                list.add(c.getValue());
            } else {
                sb.append(" and " + c.getKey() + "=?");
                list.add(c.getValue());
            }
        }

        Object[] params = new Object[list.size()];
        for (int i = 0; i < list.size(); i++) {
            params[i] = list.get(i);
        }
        long counts = (Long) db.queryFieldValue(sb.toString(), Long.class, params, 1);
        int count = (int) counts;
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return count;
    }

    /**
     * 查询全部发票
     *
     * @param cdt
     * @param page
     * @param pageSize
     * @return
     */
    public List<UserInvoiceView> getAllInvoice(Map<String, Object> cdt, int page, int pageSize) {
        //if (!cdt.containsKey("agentId")) {
            cdt.put("agentId", CloudContextUtils.getAgentId());
        //}
        List<Object> list = new ArrayList<>();
        StringBuilder sb = new StringBuilder("select ui.*,");
        sb.append("(select t.description from dic_paramindex n,dic_paramitem t where t.paramId=n.paramEName  and n.paramEName='invoice' and t.value= ui.type) as typeName,");
        sb.append("(select t.description from dic_paramindex n,dic_paramitem t where t.paramId=n.paramEName  and n.paramEName='invoiceContent' and t.value= ui.content) as contentName,");
        sb.append("(select t.description from dic_paramindex n,dic_paramitem t where t.paramId=n.paramEName  and n.paramEName='invoiceStatus' and t.value= ui.status) as statusName");
        sb.append(" from user_invoice ui where 1=1 ");

        for (Map.Entry<String, Object> c : cdt.entrySet()) {
            if (c.getKey().equals("start")) {
                sb.append(" and createTime >=?");
                list.add(c.getValue());
            } else if (c.getKey().equals("end")) {
                sb.append(" and createTime <?");
                list.add(c.getValue());
            } else {
                sb.append(" and " + c.getKey() + "=?");
                list.add(c.getValue());
            }
        }

        Object[] params = new Object[list.size()];
        for (int i = 0; i < list.size(); i++) {
            params[i] = list.get(i);
        }

        sb.append(" order by id desc ");
        if (page > 0 && pageSize > 0) {
            sb.append(String.format(" limit %d,%d", (page - 1) * pageSize, pageSize));
        }

        List<UserInvoiceView> getUserInvoice = db.queryForBeans(sb.toString(), UserInvoiceView.class, params);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return getUserInvoice;
    }

    /**
     * 删除发票记录
     *
     * @param userName
     * @param id
     * @return
     */
    public int delinvoice(String userName, int id) {
        String sql = "delete from user_invoice where userName=? and id=? and agentId=?";
        int ret = db.executeSql(sql, new Object[]{userName, id, CloudContextUtils.getAgentId()});
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    /**
     * 更新发票信息
     *
     * @return
     */
    public int uptInvoice(Map<String, Object> values, Map<String, Object> cdt) {
        //if (!cdt.containsKey("agentId")) {
            cdt.put("agentId", CloudContextUtils.getAgentId());
        //}
        int ret = db.modifyRecord("user_invoice", values, cdt);
        String code = db.getErrCode();
        this.setErrCode(code);
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }

        return ret;
    }

    /**
     * 获取发票信息
     *
     * @param id
     * @param userId
     * @return
     */
    public UserInvoiceView queryUserInvoice(int id, int userId) {
        UserInvoiceView ret = null;
        StringBuilder sb = new StringBuilder("select ui.*,");
        sb.append("(select t.description from dic_paramindex n,dic_paramitem t where t.paramId=n.paramEName  and n.paramEName='invoice' and t.value= ui.type) as typeName,");
        sb.append("(select t.description from dic_paramindex n,dic_paramitem t where t.paramId=n.paramEName  and n.paramEName='invoiceContent' and t.value= ui.content) as contentName,");
        sb.append("(select t.description from dic_paramindex n,dic_paramitem t where t.paramId=n.paramEName  and n.paramEName='deliveryInvoice' and t.value= ui.getType) as getTypeName,");
        sb.append("(select t.description from dic_paramindex n,dic_paramitem t where t.paramId=n.paramEName  and n.paramEName='invoiceStatus' and t.value= ui.status) as statusName");
        sb.append(" from user_invoice ui where 1=1 and id=? and agentId=? ");

        ret = db.queryForBean(sb.toString(), UserInvoiceView.class, new Object[]{id, CloudContextUtils.getAgentId()});
        if (userId > 0) {
            sb.append(" and userId=? ");
            ret = db.queryForBean(sb.toString(), UserInvoiceView.class, new Object[]{id, CloudContextUtils.getAgentId(), userId});
        }
        String code = db.getErrCode();
        this.setErrCode(code);
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }

        return ret;
    }

    /**
     * 查询历史记录
     *
     * @param userName
     * @return
     */
    public List<UserInvoice> queryHistory(String userName) {
        String sql = "select * from user_invoice where userName=? and name!='' and name is not null and agentId=? group by name";
        List<UserInvoice> queryHistory = db.queryForBeans(sql, UserInvoice.class, new Object[]{userName, CloudContextUtils.getAgentId()});
        String code = db.getErrCode();
        this.setErrCode(code);
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }

        return queryHistory;
    }

    /**
     * 根据ID查询数据
     *
     * @param id
     * @return
     */
    public UserInvoice queryUIById(int id) {
        String sql = "select * from user_invoice where id=? and agentId=?";
        UserInvoice queryId = db.queryForBean(sql, UserInvoice.class, new Object[]{id, CloudContextUtils.getAgentId()});
        String code = db.getErrCode();
        this.setErrCode(code);
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        return queryId;
    }


    /**
     * 查询发票模板是否存在
     *
     * @param name
     * @param userName
     * @return
     */
    public List<UserInvoice> queryName(String name, String userName) {
        String sql = "select * from user_invoice where name=? and userName=? and agentId=?";
        List<UserInvoice> queryName = db.queryForBeans(sql, UserInvoice.class, new Object[]{name, userName, CloudContextUtils.getAgentId()});
        String code = db.getErrCode();
        this.setErrCode(code);
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }

        return queryName;
    }
}